package code.c03_stackQueue.cSqQueue;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/10/3 20:40
 * @package code.c03_stackQueue.cSqQueue
 * @description 循环队列(扩容版)
 */

public class CSqQueueClass2<E> {
    public int size = 10;
    private E[] data;
    private int front, rear;

    public CSqQueueClass2() {
        data = (E[]) new Object[size];
        front = 0;
        rear = 0;
    }


    /**
     * 更新长度
     * @param newSize
     */
    public void updateSize(int newSize) {
        E[] tmp = (E[])new Object[newSize];
        System.arraycopy(data,0,tmp,0,data.length);
        data = tmp;
        size = newSize;
    }
    // ================================ 基本运算 ================================

    /**
     * 判断队列是否已满
     * @return
     */
    public boolean isFull(){
        return size == data.length;
    }

    /**
     * 判断是否队空
     *
     * @return
     */
    public boolean empty() {
        return front == rear;
    }

    /**
     * 入队操作
     *
     * @param e
     */
    public void push(E e) {
        if ((rear + 1) % size == front) {
            updateSize(size * 2);
        }
        rear = (rear + 1) % size;
        data[rear] = e;
    }

    /**
     * 出队操作
     *
     * @return
     */
    public E pop() {
        if (empty()) {
            throw new IllegalArgumentException("队空");
        }
        front = (front + 1) % size;
        return (E) data[front];
    }

    /**
     * 获取队中第一个元素
     *
     * @return
     */
    public E peek() {
        if (empty()) {
            throw new IllegalArgumentException("队空");
        }
        return data[(front + 1) % size];
    }

    public static void main(String[] args) {
        CSqQueueClass2<Integer> integerCSqQueueClass = new CSqQueueClass2<>();
        for (int i = 1; i < 100; i++) {
            integerCSqQueueClass.push(i);
            System.out.println(integerCSqQueueClass.size);
            System.out.println(i);

        }
    }
}
